package com.wenjunwu.blog.web;

import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.github.pagehelper.Page;
import com.wenjunwu.blog.common.JSONResult;
import com.wenjunwu.blog.common.PageTranslate;
import com.wenjunwu.blog.em.OptionEnum;
import com.wenjunwu.blog.entity.SystemUser;
import com.wenjunwu.blog.service.SystemUserService;

@Controller
public class SystemUserController {

	@Autowired
	private SystemUserService systemUserService;

	@RequestMapping(path = { "{option}/initReg","{option}/initReg"}, method = RequestMethod.GET)
	public ModelAndView initReg(@PathVariable String option) {
		ModelAndView mav = null;
		mav = new ModelAndView(option.concat("/register"));
		SystemUser systemUser = new SystemUser();
		mav.addObject(systemUser);
		return mav;
	}

	@RequestMapping(path = {"{option}/register"}, method = RequestMethod.POST)
	public String register(@PathVariable String option,@ModelAttribute SystemUser systemUser, RedirectAttributes model) {
		systemUser.setType(OptionEnum.parseOf(option).getValue());
		systemUserService.save(systemUser);
		model.addFlashAttribute(systemUser);
		return "redirect:/index";
	}

	@RequestMapping(path = "/initLogin", method = RequestMethod.GET)
	public ModelAndView initLogin() {
		ModelAndView mav = new ModelAndView("common".concat("/login"));
		SystemUser systemUser = new SystemUser();
		mav.addObject(systemUser);
		return mav;
	}

	@RequestMapping(path = "/about", method = RequestMethod.GET)
	public ModelAndView about() {
		ModelAndView mav = new ModelAndView("common".concat("/about"));
		return mav;
	}

	@RequestMapping(path = {"/index" })
	public String index() {
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if (principal.toString().equals("anonymousUser")) {
			return "redirect:/initLogin";
		}
		UserDetails userDetails = (UserDetails) principal;
		GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_ADMIN");
		if (userDetails.getAuthorities().contains(grantedAuthority)) {
			return "console/index";
		} else {
			return "redirect:/portal/index";
		}
	}

	@RequestMapping(path = "console/users", method = RequestMethod.GET)
	public ModelAndView users() {
		ModelAndView mav = new ModelAndView("console".concat("/").concat("users"));
		return mav;
	}

	@ResponseBody
	@RequestMapping(path = "console/systemUsers.json", method = RequestMethod.POST)
	public PageTranslate<SystemUser> getSystemUserPage(HttpServletRequest request) {
		String username = "".equals(request.getParameter("username"))?null: request.getParameter("username");
		String cname = "".equals(request.getParameter("cname"))?null: request.getParameter("cname");
		String type = "".equals(request.getParameter("type"))?null:request.getParameter("type");
		String qCreateTime = "".equals(request.getParameter("createTime"))?null:request.getParameter("createTime");
		LocalDate createTime = null;
		if(!StringUtils.isEmpty(qCreateTime)) {
			 createTime = LocalDate.parse(qCreateTime);
		}
		String draw = request.getParameter("draw") == null ? "1" : request.getParameter("draw");
		String paramPageNum = request.getParameter("start") == null ? "1" : request.getParameter("start");
		Integer pageSize = Integer.valueOf(request.getParameter("length") == null ? "10" : request.getParameter("length"));
		Integer pageNum = (Integer.valueOf(paramPageNum) / pageSize + 1);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("username", username);
		params.put("cname", cname);
		params.put("type", type);
		params.put("createTime", createTime);
		Page<SystemUser> usersPage = systemUserService.findUsersPage(pageNum, pageSize,params);
		PageTranslate<SystemUser> translate = new PageTranslate<SystemUser>();
		List<SystemUser> result = usersPage.getResult();
		translate.setData(result);
		translate.setDraw(Long.valueOf(draw));
		translate.setRecordsTotal(usersPage.getTotal());
		translate.setRecordsFiltered(usersPage.getTotal());
		translate.setResultCode(OptionEnum.OPTION_SUCCESS.getValue());
		return translate;
	}

	@RequestMapping(path = "console/comments", method = RequestMethod.GET)
	public ModelAndView comment() {
		ModelAndView mav = new ModelAndView("console".concat("/").concat("comments"));
		return mav;
	}

	@ResponseBody
	@RequestMapping(path = "portal/checkuser.json", method = RequestMethod.POST)
	public JSONResult checkUser(HttpServletRequest request) {
		String username = request.getParameter("username");
		if (systemUserService.checkUser(username)) {
			JSONResult result = new JSONResult();
			result.setResultCode("no");
			result.setResultContent("用户名[" + username + "]已注册！");
			return result;
		} else {
			JSONResult result = new JSONResult();
			result.setResultCode("yes");
			result.setResultContent("用户名[" + username + "]可注册！");
			return result;
		}
	}
	
	@ResponseBody
	@RequestMapping(path = "console/freezeUser/{id}", method = RequestMethod.POST)
	public JSONResult freeUser(@PathVariable Long id) {
		SystemUser systemUser =	new SystemUser();
		systemUser.setId(id);
		systemUser.setStatus(OptionEnum.OPTION_INVALID.getValue());
		systemUser.setUpdateTime(new Date());
		if ( systemUserService.updateUser(systemUser)) {
			JSONResult result = new JSONResult();
			result.setResultCode(OptionEnum.OPTION_SUCCESS.getValue());
			result.setResultContent("用户【"+id+"】已成功冻结！");
			return result;
		} else {
			JSONResult result = new JSONResult();
			result.setResultCode(OptionEnum.OPTION_FAILURE.getValue());
			result.setResultContent("用户【"+id+"】冻结失败");
			return result;
		}
	}
	
	@ResponseBody
	@RequestMapping(path = "console/unFreezeUser/{id}", method = RequestMethod.POST)
	public JSONResult unFreeUser(@PathVariable Long id) {
		SystemUser systemUser =	new SystemUser();
		systemUser.setId(id);
		systemUser.setStatus(OptionEnum.OPTION_INVALID.getValue());
		systemUser.setUpdateTime(new Date());
		if (systemUserService.updateUser(systemUser)) {
			JSONResult result = new JSONResult();
			result.setResultCode(OptionEnum.OPTION_SUCCESS.getValue());
			result.setResultContent("用户【"+id+"】已成功解冻");
			return result;
		} else {
			JSONResult result = new JSONResult();
			result.setResultCode(OptionEnum.OPTION_FAILURE.getValue());
			result.setResultContent("用户【"+id+"】解冻失败");
			return result;
		}
	}
}
